package com.zpark.controller;

import com.zpark.dao.GroupA;
import com.zpark.pojo.Person;
import com.zpark.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Length;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.groups.Default;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/user")
@Validated
public class UserController {
    /**
     * localhost:8080//user/user1?name=username&address="北京"&age=20&email=12345@qq.com
     *javabean参数校验
     * @param user
     * @param result
     * @return
     */
    @PostMapping(path = "/check")
    public String check(@RequestBody @Valid User user, BindingResult result) {
        String name = user.getName();
        if (result.hasErrors()) {
            List<ObjectError> list = result.getAllErrors();
            for (ObjectError error : list) {
                System.out.println(error.getCode() + "_" + error.getDefaultMessage());
            }
        }
        return name;
    }
    // URL参数校验
    @RequestMapping("/test")
    public String query(@Length(min = 2, max = 10, message = "姓名长度错误，姓名长度2-10！") String name
            , @Min(value = 1, message = "年龄最小只能1")
                        @Max(value = 99, message = "年龄最大只能99")
                        @RequestParam(name = "age", required = true) int age) {
        System.out.println(name + "," + age);
        return name + "," + age;
    }
    //分组验证
//    @RequestMapping("/save3")
//    public String save(@RequestBody @Validated({GroupA.class, Default.class}) Person person, BindingResult result){
//        System.out.println(JSON.toJSONString(result.getAllErrors()));
//        return "success";
//    }

}